package com.heima.search.service.impl;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl  implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 新增搜索记录
     * @param keyword
     * @param userId
     */
    @Override
    public void insert(String keyword, Integer userId) {

        //1.判断此关键字是否已经存在
        //参数1：查询条件   参数2：返回值类型
        //wherer userid = 1 and keyword = xx
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if(apUserSearch != null){
            //2.如果存在，更新时间即可
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.如果不存在，判断记录数量是否>=10条
        Query queryAll = Query.query(Criteria.where("userId").is(userId));
        //添加一个排序
        queryAll.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(queryAll, ApUserSearch.class);

        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());
        userSearch.setUserId(userId);

        if(apUserSearches != null && apUserSearches.size() < 10){
            //4.如果小于10条，直接新增
            mongoTemplate.save(userSearch);
        }else{
            //5.如果大于等于10条，删除最老的，添加最新的
            //干掉最老的，添加最新的
            mongoTemplate.remove(apUserSearches.get(apUserSearches.size()-1));
            mongoTemplate.save(userSearch);
        }
    }

    /**
     * 加载用户搜索记录，记得排个序
     * @return
     */
    @Override
    public ResponseResult load() {
        //1.获得登录的用户
        ApUser user = ApUserThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.根据用户ID，排序查询即可
        Query query = Query.query(Criteria.where("userId").is(user.getId()));
        //排序
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }
}
